package com.xing.crm.service.impl;

import com.xing.crm.mapper.ProApplyMapper;
import com.xing.crm.mapper.ProRoleMapper;
import com.xing.crm.pojo.*;
import com.xing.crm.service.ProApplyService;
import com.xing.crm.service.ProShopService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Mr.L
 * @version V1.0
 * @date 2021年08月09日 17:57
 */
@Transactional(rollbackFor = Exception.class)
@Service
public class ProApplyServiceImpl implements ProApplyService {
	
	@Resource
	private ProApplyMapper proApplyMapper;
	@Resource
	private ProShopService proShopService;
	@Resource
	private ProRoleMapper proRoleMapper;
	
	@Override
	public Map<String, Object> submitApply(ProApply proApply, WebUser webUser) {
		Map result = new HashMap(0);
		int code = 1;
		String msg = "请不要重复申请";
		ProApply data = proApplyMapper.checked(proApply);
		ProShop shop = proShopService.getShopByUid(webUser);
		if(data == null && shop == null) {
			proApplyMapper.submitApply(proApply);
			code = 0;
			msg = "申请成功";
		}
		result.put("code", code);
		result.put("msg", msg);
		
		return result;
	}
	
	@Override
	public PageResult<ProApply> getApplies(ProShop proShop, Boolean isManager) {
		PageResult<ProApply> result = new PageResult();
		result.setCode(0);
		result.setMsg("没有权限");
		/* 店长获取待审核列表 */
		if(isManager != null && isManager && proShop != null) {
			List<ProApply> data = proApplyMapper.getApplies(proShop.getId());
			result.setData(data);
			result.setCount(data.size());
			result.setMsg("查询成功");
		}
		return result;
	}
	
	@Override
	public PageResult agreeApply(String id, Boolean isManager) {
		PageResult result = new PageResult();
		result.setCode(-1);
		result.setMsg("操作失败");
		/* 店长同意申请 */
		if(isManager != null && isManager && !StringUtils.isEmpty(id)) {
			/* 获取申请人、申请店铺 */
			ProApply apply = proApplyMapper.get(id);
			if(apply != null) {
				/* 申请人 */
				WebUser user = new WebUser();
				user.setId(apply.getUserId());
				/* 是否已加入店铺 */
				ProShop shop = proShopService.getShopByUid(user);
				/**/
				ProRole role = proRoleMapper.getUserRole(user.getId());
				/* 加入店铺，删除申请记录 */
				if(shop == null && role == null) {
					role = proRoleMapper.getRoleByName("店员");
					proApplyMapper.agreeApply(apply);
					proRoleMapper.insertUserRole(user.getId(), role.getId());
					proApplyMapper.deleteApply(apply);
					result.setCode(0);
					result.setMsg("操作成功");
				}
			}
		}
		
		return result;
	}
}
